<template>
  <div class="pan-cache-management">
    <!-- 缓存统计卡片区域 -->
    <el-card class="stats-card" :body-style="{ padding: '15px' }">
      <div class="stats-container">
        <StatisticCard
          label="Redis状态"
          :value="
            statistics.redis_status
              ? statistics.redis_status.connected
                ? '正常'
                : '异常'
              : '-'
          "
          icon="el-icon-connection"
          :type="statistics.redis_status?.connected ? 'success' : 'danger'"
        />
        <StatisticCard
          label="内存使用"
          :value="
            statistics.memory_info
              ? `${statistics.memory_info.memory_usage_percentage}%`
              : '-'
          "
          icon="el-icon-cpu"
          :type="getMemoryType(statistics.memory_info?.memory_usage_percentage)"
        />
        <StatisticCard
          label="缓存命中率"
          :value="
            statistics.performance_stats
              ? `${statistics.performance_stats.hit_rate}%`
              : '-'
          "
          icon="el-icon-aim"
          :type="getHitRateType(statistics.performance_stats?.hit_rate)"
        />
        <StatisticCard
          label="低分资产"
          :value="
            statistics.low_score_results
              ? statistics.low_score_results.total_count.toString()
              : '0'
          "
          icon="el-icon-document"
          type="warning"
        />
      </div>
      <div v-if="statistics.memory_info" class="stats-detail">
        <div class="memory-detail">
          <span
            >内存使用: {{ statistics.memory_info.used_memory_human }} /
            {{ statistics.memory_info.maxmemory_human }}</span
          >
        </div>
        <div v-if="statistics.keyspace_info" class="keyspace-detail">
          <span>总键数: {{ statistics.keyspace_info.total_keys || 0 }}</span>
          <span
            >过期键数: {{ statistics.keyspace_info.expires_keys || 0 }}</span
          >
          <span
            >平均TTL: {{ formatTTL(statistics.keyspace_info.avg_ttl) }}</span
          >
        </div>
        <div v-if="statistics.low_score_results" class="low-score-detail">
          <span
            >活跃: {{ statistics.low_score_results.active_count || 0 }}</span
          >
          <span
            >即将过期:
            {{ statistics.low_score_results.near_expired_count || 0 }}</span
          >
          <span>总计: {{ statistics.low_score_results.total_count || 0 }}</span>
        </div>
        <div v-if="statistics.generated_at" class="generated-time">
          统计时间: {{ statistics.generated_at }}
        </div>
      </div>
    </el-card>

    <!-- 筛选区域 -->
    <el-card class="filter-card" :body-style="{ padding: '15px' }">
      <div class="filter-content">
        <DynamicForm
          ref="searchFormRef"
          v-model="filterForm"
          :form-config="filterFormConfig"
          :gutter="16"
          label-width="100px"
          type="search"
          @search="handleSearch"
          @reset="handleReset"
        />
      </div>
    </el-card>

    <!-- 低分资产列表 -->
    <el-card class="table-card" :body-style="{ padding: '15px' }">
      <div v-loading="loading" class="table-wrapper">
        <DynamicTable
          :data="assetList"
          :columns="tableColumns"
          :loading="loading"
          :pagination="pagination"
          border
          row-key="temp_id"
          @selection-change="handleSelectionChange"
          @size-change="handleSizeChange"
          @current-page-change="handlePageChange"
        >
          <template #table-top>
            <div class="list-header">
              <div class="batch-actions">
                <el-button
                  type="success"
                  :disabled="selectedAssets.length === 0"
                  @click="handleBatchConfirm"
                >
                  批量确认入库
                </el-button>
                <el-button
                  type="warning"
                  :disabled="selectedAssets.length === 0"
                  @click="handleBatchIgnore"
                >
                  批量忽略
                </el-button>
                <el-button
                  type="danger"
                  :disabled="selectedAssets.length === 0"
                  @click="handleBatchDelete"
                >
                  批量删除
                </el-button>
              </div>
              <div class="header-right">
                <span class="sort-label">排序:</span>
                <el-select
                  v-model="filterForm.sort_by"
                  size="small"
                  style="width: 140px; margin-right: 10px"
                  @change="handleSearch"
                >
                  <el-option label="按缓存时间" value="cached_at" />
                  <el-option label="按风险评分" value="risk_score" />
                </el-select>
                <el-select
                  v-model="filterForm.sort_order"
                  size="small"
                  style="width: 80px"
                  @change="handleSearch"
                >
                  <el-option label="升序" value="asc" />
                  <el-option label="降序" value="desc" />
                </el-select>
              </div>
            </div>
          </template>

          <template #risk_score="{ row }">
            <el-tag :type="getRiskTagType(row.risk_assessment?.risk_score)">
              {{ row.risk_assessment?.risk_score || 0 }} 分
            </el-tag>
          </template>

          <template #risk_level="{ row }">
            <el-tag
              :type="getRiskLevelTag(row.risk_assessment?.risk_level)"
              size="small"
            >
              {{ getRiskLevelText(row.risk_assessment?.risk_level) }}
            </el-tag>
          </template>

          <template #action="{ row }">
            <el-button
              size="small"
              type="primary"
              @click="handleViewDetail(row)"
            >
              详情
            </el-button>
            <el-button
              size="small"
              type="success"
              @click="handleConfirmAsset(row)"
            >
              确认入库
            </el-button>
            <el-button
              size="small"
              type="warning"
              @click="handleIgnoreAsset(row)"
            >
              忽略
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDeleteAsset(row)"
            >
              删除
            </el-button>
          </template>
        </DynamicTable>
      </div>
    </el-card>

    <!-- 资产详情弹窗 -->
    <AssetDetailModal v-model="detailVisible" :temp-id="currentTempId" />

    <!-- 批量确认弹窗 -->
    <BatchConfirmModal
      v-model="batchConfirmVisible"
      :selected-count="selectedAssets.length"
      :department-options="props.departmentOptions"
      @confirm="handleBatchConfirmSubmit"
    />

    <!-- 批量忽略弹窗 -->
    <BatchIgnoreModal
      v-model="batchIgnoreVisible"
      :selected-count="selectedAssets.length"
      @confirm="handleBatchIgnoreSubmit"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import DynamicForm from "@/components/DynamicForm/index.vue";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import type { FormItemConfig } from "@/components/DynamicForm/types";
import type {
  TableColumn,
  PaginationConfig,
} from "@/components/DynamicTable/types";
import StatisticCard from "./components/StatisticCard.vue";
import AssetDetailModal from "./components/AssetDetailModal.vue";
import BatchConfirmModal from "./components/BatchConfirmModal.vue";
import BatchIgnoreModal from "./components/BatchIgnoreModal.vue";

// 定义props
const props = defineProps<{
  task?: string;
  departmentOptions?: Array<{ label: string; value: string }>;
}>();

import {
  getCacheStatistics,
  getCacheAssets,
  getCacheAssetDetail,
  batchConfirmCacheAssets,
  batchIgnoreCacheAssets,
  deleteCacheAsset,
  batchDeleteCacheAssets,
  getPanTasks,
} from "../../servers";

// 页面状态
const loading = ref(false);
const selectedAssets = ref<any[]>([]);
const detailVisible = ref(false);
const currentTempId = ref<string | null>(null);
const batchConfirmVisible = ref(false);
const batchIgnoreVisible = ref(false);

// 统计数据
const statistics = reactive<any>({
  redis_status: null,
  memory_info: null,
  performance_stats: null,
  cache_distribution: null,
  low_score_results: null,
  keyspace_info: null,
  generated_at: null,
  time_range: null,
});

// 资产列表数据
const assetList = ref<any[]>([]);

// 筛选表单
const searchFormRef = ref<DynamicFormInstance>();
const filterForm = reactive({
  task_id: "",
  min_risk_score: "",
  max_risk_score: "",
  keyword: "",
  sort_by: "cached_at",
  sort_order: "desc",
});

// 任务选项列表
const taskOptions = ref<Array<{ label: string; value: number }>>([]);

// 筛选表单配置
const filterFormConfig = computed(() => {
  return [
    {
      key: "task_id",
      name: "任务ID",
      type: "select",
      placeholder: "请选择任务",
      params: { clearable: true },
      options: [{ label: "全部", value: "" }, ...taskOptions.value],
      col: { span: 6 },
    },
    {
      key: "min_risk_score",
      name: "最低评分",
      type: "input-number",
      placeholder: "最低风险评分",
      params: { min: 0, max: 100 },
      col: { span: 6 },
    },
    {
      key: "max_risk_score",
      name: "最高评分",
      type: "input-number",
      placeholder: "最高风险评分",
      params: { min: 0, max: 100 },
      col: { span: 6 },
    },
    {
      key: "keyword",
      name: "关键词",
      type: "input",
      placeholder: "请输入关键词",
      col: { span: 6 },
    },
  ] as FormItemConfig[];
});

// 表格列配置
const tableColumns: TableColumn[] = [
  {
    type: "selection",
    width: 55,
    label: "",
  },
  {
    label: "搜索ID",
    prop: "search_id",
    minWidth: 150,
  },
  {
    label: "关键词",
    prop: "keyword",
    minWidth: 120,
  },
  {
    label: "文件名",
    prop: "original_data",
    minWidth: 200,
    render: (row: any) => row.original_data?.filename || "-",
  },
  {
    label: "风险评分",
    prop: "risk_assessment",
    width: 120,
    align: "center",
    slot: "risk_score",
  },
  {
    label: "风险等级",
    prop: "risk_assessment",
    width: 100,
    align: "center",
    slot: "risk_level",
  },
  {
    label: "缓存时间",
    prop: "cached_at",
    width: 160,
  },
  {
    label: "操作",
    width: 350,
    fixed: "right",
    slot: "action",
  },
];

// 分页配置
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next, jumper",
  background: true,
});

// 获取内存使用类型
const getMemoryType = (
  percentage?: number
): "success" | "warning" | "danger" | "info" => {
  if (!percentage) return "info";
  if (percentage >= 90) return "danger";
  if (percentage >= 70) return "warning";
  return "success";
};

// 获取命中率类型
const getHitRateType = (
  hitRate?: number
): "success" | "warning" | "danger" | "info" => {
  if (!hitRate) return "info";
  if (hitRate >= 90) return "success";
  if (hitRate >= 70) return "warning";
  return "danger";
};

// 获取风险评分标签类型
const getRiskTagType = (
  score?: number
): "success" | "warning" | "danger" | "info" => {
  if (!score) return "info";
  if (score >= 80) return "danger";
  if (score >= 60) return "warning";
  return "info";
};

// 获取风险等级标签类型
const getRiskLevelTag = (
  level?: string
): "success" | "warning" | "danger" | "info" => {
  const typeMap: Record<string, "success" | "warning" | "danger" | "info"> = {
    high: "danger",
    medium: "warning",
    low: "info",
  };
  return typeMap[level || ""] || "info";
};

// 获取风险等级文本
const getRiskLevelText = (level?: string): string => {
  const textMap: Record<string, string> = {
    high: "高风险",
    medium: "中风险",
    low: "低风险",
  };
  return textMap[level || ""] || "未知";
};

// 格式化TTL（秒转可读格式）
const formatTTL = (seconds?: number): string => {
  if (!seconds || seconds === 0) return "无";
  if (seconds < 60) return `${seconds}秒`;
  if (seconds < 3600) return `${Math.floor(seconds / 60)}分钟`;
  if (seconds < 86400) return `${Math.floor(seconds / 3600)}小时`;
  return `${Math.floor(seconds / 86400)}天`;
};

// 获取缓存统计
const fetchCacheStatistics = async () => {
  try {
    const result = await getCacheStatistics({
      time_range: "24h",
      include_details: true,
    });


      // 根据实际返回数据结构更新统计信息
      Object.assign(statistics, {
        redis_status: result.data.redis_status || null,
        memory_info: result.data.memory_info || null,
        performance_stats: result.data.performance_stats || null,
        cache_distribution: result.data.cache_distribution || null,
        low_score_results: result.data.low_score_results || null,
        keyspace_info: result.data.keyspace_info || null,
        generated_at: result.data.generated_at || null,
        time_range: result.data.time_range || null,
      });

  } catch (error: any) {
    console.error("获取缓存统计失败:", error);
    ElMessage.error("获取缓存统计失败");
  }
};

// 获取任务列表（用于下拉选择）
const fetchTaskList = async () => {
  try {
    const result = await getPanTasks({
      page: 1,
      per_page: 100,
    });

    taskOptions.value = result.data.tasks.map((task: any) => ({
      label: `${task.task_name || task.task_code} (${task.task_code})`,
      value: task.task_id || task.id,
    }));
  } catch (error: any) {
    console.error("获取任务列表失败:", error);
  }
};

// 获取资产列表
const fetchAssetList = async () => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      per_page: pagination.pageSize,
      sort_by: filterForm.sort_by,
      sort_order: filterForm.sort_order,
    };

    // 处理筛选参数
    if (filterForm.task_id) {
      params.task_id = Number(filterForm.task_id);
    }
    if (filterForm.min_risk_score) {
      params.min_risk_score = Number(filterForm.min_risk_score);
    }
    if (filterForm.max_risk_score) {
      params.max_risk_score = Number(filterForm.max_risk_score);
    }
    if (filterForm.keyword) {
      params.keyword = filterForm.keyword;
    }

    const result = await getCacheAssets(params);

    assetList.value = result.data.assets || [];

    // 更新分页信息
    if (result.data.pagination) {
      pagination.total = result.data.pagination.total || 0;
      pagination.currentPage = result.data.pagination.page || 1;
      pagination.pageSize = result.data.pagination.per_page || 20;
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取资产列表失败");
  } finally {
    loading.value = false;
  }
};

// 筛选操作
const handleReset = () => {
  searchFormRef.value?.resetFields();
  filterForm.task_id = "";
  filterForm.min_risk_score = "";
  filterForm.max_risk_score = "";
  filterForm.keyword = "";
  filterForm.sort_by = "cached_at";
  filterForm.sort_order = "desc";
  pagination.currentPage = 1;
  fetchAssetList();
};

const handleSearch = (values: any) => {
  pagination.currentPage = 1;
  fetchAssetList();
};

// 分页操作
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchAssetList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchAssetList();
};

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedAssets.value = selection;
};

// 查看详情
const handleViewDetail = (row: any) => {
  currentTempId.value = row.temp_id;
  detailVisible.value = true;
};

// 确认单个资产
const handleConfirmAsset = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要确认资产【${row.original_data?.filename}】入库吗？`,
      "确认入库",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    loading.value = true;
    const result = await batchConfirmCacheAssets({
      temp_ids: [row.temp_id],
    });

    if (result.code === 200) {
      ElMessage.success("确认入库成功");
      fetchAssetList();
      fetchCacheStatistics(); // 刷新统计
    } else {
      ElMessage.error(result.message || "确认入库失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "操作失败");
    }
  } finally {
    loading.value = false;
  }
};

// 忽略单个资产
const handleIgnoreAsset = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要忽略资产【${row.original_data?.filename}】吗？`,
      "忽略确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    loading.value = true;
    const result = await batchIgnoreCacheAssets({
      temp_ids: [row.temp_id],
    });

    if (result.code === 200) {
      ElMessage.success("忽略成功");
      fetchAssetList();
      fetchCacheStatistics(); // 刷新统计
    } else {
      ElMessage.error(result.message || "忽略失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "操作失败");
    }
  } finally {
    loading.value = false;
  }
};

// 删除单个资产
const handleDeleteAsset = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除资产【${row.original_data?.filename}】吗？此操作不可恢复！`,
      "删除确认",
      {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    loading.value = true;
    const result = await deleteCacheAsset(row.temp_id);

    if (result.code === 200) {
      ElMessage.success("删除成功");
      fetchAssetList();
      fetchCacheStatistics(); // 刷新统计
    } else {
      ElMessage.error(result.message || "删除失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "操作失败");
    }
  } finally {
    loading.value = false;
  }
};

// 批量确认
const handleBatchConfirm = () => {
  if (selectedAssets.value.length === 0) {
    ElMessage.warning("请先选择要确认的资产");
    return;
  }
  batchConfirmVisible.value = true;
};

// 批量确认提交
const handleBatchConfirmSubmit = async (formData: {
  responsible_department?: string;
  responsible_person?: string;
  confirm_reason?: string;
}) => {
  batchConfirmVisible.value = false;
  loading.value = true;
  try {
    const tempIds = selectedAssets.value.map((item) => item.temp_id);
    const result = await batchConfirmCacheAssets({
      temp_ids: tempIds,
      ...formData,
    });

    if (result.code === 200) {
      const successCount = result.data?.confirmed_count || 0;
      const failCount = result.data?.failed_count || 0;
      if (failCount > 0) {
        ElMessage.warning(
          `批量确认完成：成功 ${successCount} 个，失败 ${failCount} 个`
        );
      } else {
        ElMessage.success(`批量确认成功，共 ${successCount} 个资产`);
      }
      selectedAssets.value = [];
      fetchAssetList();
      fetchCacheStatistics(); // 刷新统计
    } else {
      ElMessage.error(result.message || "批量确认失败");
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "操作失败");
  } finally {
    loading.value = false;
  }
};

// 批量忽略
const handleBatchIgnore = () => {
  if (selectedAssets.value.length === 0) {
    ElMessage.warning("请先选择要忽略的资产");
    return;
  }
  batchIgnoreVisible.value = true;
};

// 批量忽略提交
const handleBatchIgnoreSubmit = async (formData: {
  ignore_reason?: string;
}) => {
  batchIgnoreVisible.value = false;
  loading.value = true;
  try {
    const tempIds = selectedAssets.value.map((item) => item.temp_id);
    const result = await batchIgnoreCacheAssets({
      temp_ids: tempIds,
      ...formData,
    });

    if (result.code === 200) {
      const successCount = result.data?.ignored_count || 0;
      const failCount = result.data?.failed_count || 0;
      if (failCount > 0) {
        ElMessage.warning(
          `批量忽略完成：成功 ${successCount} 个，失败 ${failCount} 个`
        );
      } else {
        ElMessage.success(`批量忽略成功，共 ${successCount} 个资产`);
      }
      selectedAssets.value = [];
      fetchAssetList();
      fetchCacheStatistics(); // 刷新统计
    } else {
      ElMessage.error(result.message || "批量忽略失败");
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "操作失败");
  } finally {
    loading.value = false;
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedAssets.value.length === 0) {
    ElMessage.warning("请先选择要删除的资产");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要批量删除 ${selectedAssets.value.length} 个资产吗？此操作不可恢复！`,
      "批量删除确认",
      {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    loading.value = true;
    const tempIds = selectedAssets.value.map((item) => item.temp_id);
    const result = await batchDeleteCacheAssets({
      temp_ids: tempIds,
    });

    if (result.code === 200) {
      const successCount = result.data?.deleted_count || 0;
      const failCount = result.data?.failed_count || 0;
      if (failCount > 0) {
        ElMessage.warning(
          `批量删除完成：成功 ${successCount} 个，失败 ${failCount} 个`
        );
      } else {
        ElMessage.success(`批量删除成功，共 ${successCount} 个资产`);
      }
      selectedAssets.value = [];
      fetchAssetList();
      fetchCacheStatistics(); // 刷新统计
    } else {
      ElMessage.error(result.message || "批量删除失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "操作失败");
    }
  } finally {
    loading.value = false;
  }
};

// 初始化
onMounted(() => {
  fetchCacheStatistics();
  fetchTaskList();
  fetchAssetList();
});
</script>

<style scoped lang="scss">
.pan-cache-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .stats-card,
  .filter-card,
  .table-card {
    margin-bottom: 20px;
    border-radius: 8px;
    border: 1px solid #f0f0f0;
  }

  .stats-container {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
  }

  .stats-detail {
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px solid #f0f0f0;
    font-size: 12px;
    color: #909399;

    .memory-detail,
    .keyspace-detail,
    .low-score-detail {
      display: flex;
      gap: 20px;
      margin-bottom: 8px;
      flex-wrap: wrap;

      span {
        padding: 4px 8px;
        background-color: #f5f7fa;
        border-radius: 4px;
      }
    }

    .generated-time {
      text-align: right;
      color: #c0c4cc;
      font-size: 11px;
    }
  }

  .filter-content {
    padding: 5px 0;
  }

  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;

    .batch-actions {
      display: flex;
      gap: 10px;
    }

    .header-right {
      display: flex;
      align-items: center;
      gap: 10px;

      .sort-label {
        color: #606266;
        font-size: 14px;
      }
    }
  }

  .table-wrapper {
    min-height: 200px;
  }
}
</style>
